package com.zjun.demo.experimentaldemo.indexbar

import android.content.Context
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.common.reflect.TypeToken
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.zjun.demo.experimentaldemo.R
import com.zjun.demo.experimentaldemo.base.BaseActivity
import com.zjun.demo.experimentaldemo.databinding.ActivityIndexBarViewBinding
import com.zjun.demo.experimentaldemo.indexbar.suspension.SuspensionDecoration
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream
import java.io.InputStreamReader
import java.util.Locale

/**
 * 自定义侧滑索引与recycleView联动
 */
class IndexBarActivity : BaseActivity<ActivityIndexBarViewBinding>(),
    IndexBarView.OnIndexPressedListener {


    private lateinit var mLinearLayoutManager: LinearLayoutManager

    private val mCategorySet = mutableSetOf<String>()

    private lateinit var mCountryAdapter: CountryAdapter

    override fun getLayoutId(): Int = R.layout.activity_index_bar_view

    override fun initialize() {
        mBinding.indexBarView.onIndexListener = this
        initCountryRecycleView()
    }

    private fun initCountryRecycleView() {
        val locale = resources.configuration.locales.get(0)
        val sortLocale:Locale
        language = locale.language
        val json = when (language) {
            "zh" -> {
                sortLocale = Locale("zh")
                loadRawJson(this, R.raw.zh)
            }
            "de" -> {
                sortLocale = Locale("de")
                loadRawJson(this, R.raw.de)
            }
            "es" -> {
                sortLocale = Locale("es")
                loadRawJson(this, R.raw.es)
            }
            "fr" -> {
                sortLocale = Locale("fr")
                loadRawJson(this, R.raw.fr)
            }
            "ja" -> {
                sortLocale = Locale("ja")
                loadRawJson(this, R.raw.ja)
            }
            "it" -> {
                sortLocale = Locale("it")
                loadRawJson(this, R.raw.it)
            }
            else -> {
                sortLocale = Locale("en")
                loadRawJson(this, R.raw.en)
            }
        }
        val moshi = Moshi.Builder().build()
        val jsonAdapter: JsonAdapter<List<CountryEntity>> = moshi.adapter(object : TypeToken<List<CountryEntity>>() {}.type)
        val countryEntities = jsonAdapter.fromJson(json)?: mutableListOf()
        PinyinUtil.sortByLocale(sortLocale, countryEntities)
        var suspensionTag = ""
        countryEntities.forEachIndexed { _, countryEntity ->
            if (suspensionTag != countryEntity.getSuspensionTag()) {
                suspensionTag = countryEntity.getSuspensionTag()
                countryEntity.setShowSuspension(true)
            } else {
                countryEntity.setShowSuspension(false)
            }
            mCategorySet.add(countryEntity.getSuspensionTag())
        }
        mBinding.indexBarView.updateIndexData(mCategorySet.toTypedArray(), index = 0)
        mBinding.rvCountry.run {
            addOnScrollListener(object : RecyclerView.OnScrollListener() {

                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    super.onScrolled(recyclerView, dx, dy)
                    val position = mLinearLayoutManager.findFirstVisibleItemPosition()
                    val tag = mCountryAdapter.data[position].getSuspensionTag()
                    mBinding.indexBarView.updateIndex(tag)
                }
            })
            layoutManager = LinearLayoutManager(this@IndexBarActivity).apply {
                mLinearLayoutManager = this
            }
            addItemDecoration(SuspensionDecoration())
            adapter = CountryAdapter().apply {
                setList(countryEntities)
                mCountryAdapter = this
            }
        }
    }

    override fun onClick(v: View) {
        when (v.id) {

        }
    }

    override fun onIndexPressed(index: Int, text: String) {
        mBinding.run {
            tvSideBarHint.text = text
            tvSideBarHint.isVisible = true
            val position = mCountryAdapter.data.indexOfFirst { it.getSuspensionTag() == text }
            if (position != -1) {
                mLinearLayoutManager.scrollToPositionWithOffset(position, 0)
            }
        }
    }

    override fun onMotionEventEnd() {
        mBinding.tvSideBarHint.isVisible = false
    }

    private fun loadRawJson(context: Context, resId: Int): String {
        val stringBuilder = StringBuilder()
        try {
            val inputStream: InputStream = context.resources.openRawResource(resId)
            val inputStreamReader = InputStreamReader(inputStream)
            val bufferedReader = BufferedReader(inputStreamReader)
            var line: String?
            while (bufferedReader.readLine().also { line = it } != null) {
                stringBuilder.append(line)
            }
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return stringBuilder.toString()
    }

    companion object {

        var language: String = "en"

    }

}